Modern C++ Design by Andrei Alexandrescu

Modern C++ Design by Andrei Alexandrescu

Author:Andrei Alexandrescu
Language: eng
Format: epub
Publisher: Pearson Education Limited (US titles)
Published: 2001-01-11T05:00:00+00:00


7.1. Smart Pointers 101

So what’s a smart pointer? A smart pointer is a C++ class that mimics a regular pointer in syntax and some semantics, but it does more. Because smart pointers to different types of objects tend to have a lot of code in common, almost all good-quality smart pointers in existence are templated by the pointee type, as you can see in the following code:

Click here to view code image

template <class T>

class SmartPtr

{

public:

explicit SmartPtr(T* pointee) : pointee_(pointee) {...}

SmartPtr& operator=(const SmartPtr& other);

~SmartPtr();

T& operator*() const

{

...

return *pointee_;

}

T* operator->() const

{

...

return pointee_;

}

private:

T* pointee_;

...

};

SmartPtr<T> aggregates a pointer to T in its member variable pointee_. That’s what most smart pointers do. In some cases, a smart pointer might aggregate some handles to data and compute the pointer on the fly.

The two operators give SmartPtr pointer-like syntax and semantics. That is, you can write

class Widget

{

public:

void Fun();

};



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.